<script setup>

import {ref} from "vue";
import {updatePwdReq} from "@/api/user";
import {ElMessage} from "element-plus";
import router from "@/router/router";
import {userInfoStore} from "@/stores/userinfo.js";

const userStore = userInfoStore();

//校验新老密码规则
const validateSamePass = (rule, value, callback) => {
  if(value === passwordForm.value.old_pwd){
    callback(new Error('新密码与原密码不能一样'))
  }else callback()
}

//校验新密码与确认密码规则
const validateNoSamePass = (rule, value, callback) => {
  if(value !== passwordForm.value.new_pwd){
    callback(new Error('两次输入的密码不一致'))
  }else callback()
}

const rules={
  old_new:[
    //非空校验
    { required: true, message: '请输入原密码', trigger: 'blur' },
  ],
  new_pwd:[
    //非空校验
    { required: true, message: '新密码不能为空', trigger: 'blur' },
    //长度校验
    { min:5,max:15,message: '新密码长度应为5-16', trigger: 'blur' },
    //自定义校验
    {validator:validateSamePass,trigger: 'blur'}
  ],
  re_pwd:[
    //非空校验
    { required: true, message: '确认密码不能为空', trigger: 'blur' },
    //长度校验
    { min:5,max:15,message: '确认密码长度应为5-16', trigger: 'blur' },
    //自定义校验
    {validator:validateNoSamePass,trigger: 'blur'}
  ]
}


//表单模型
const passwordForm=ref({
  old_pwd:'',
  new_pwd:'',
  re_pwd:''
})

//校验规则引用
const formRef = ref()

const updatePassword = async () => {
  //等待校验通过
  await formRef.value.validate()
  //发送请求
  let result = await updatePwdReq(passwordForm.value)
  ElMessage.success(result.message)
  //退出登录
  userStore.setUserInfo('')
  await router.push('/login')
}

</script>

<template>
  <el-card class="card-container">
    <template #header>
      <div class="card-header">
        <span>修改密码</span>
      </div>
    </template>
    <el-row>
      <el-col :span="12">
        <el-form ref="formRef" :model="passwordForm" :rules="rules" label-width="80px">
          <el-form-item prop="old_pwd" label="原密码：">
            <el-input v-model="passwordForm.old_pwd"></el-input>
          </el-form-item>
          <el-form-item prop="new_pwd" label="新密码：">
            <el-input v-model="passwordForm.new_pwd"></el-input>
          </el-form-item>
          <el-form-item prop="re_pwd" label="确认密码">
            <el-input v-model="passwordForm.re_pwd"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="updatePassword()">修改密码</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </el-card>
</template>

<style scoped>
@import "@/assets/base.css";

</style>